#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/02/12
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from flask import Blueprint, render_template, redirect, url_for, request, json, session, abort
from flask_login import login_required,current_user
from project.define import app_logger
from project.prepare import CarParkService
from .page import Messager


# 收费功能
charge = Blueprint(name='charge', import_name='project', url_prefix='/charge', template_folder='routes/charge/html')
PageMessager = Messager()
RouterName = "charge"


@charge.route('/')
@login_required
def default():
    """
    重定向
    """
    return redirect(url_for('charge.preview'))


@charge.route('/preview', methods=['POST', 'GET'])
@login_required
def preview():
    """
    收费界面
    """
    view = "preview"
    if request.method == 'POST':
        try:
            # 检查数据类型
            p_data = request.get_json()
            if not isinstance(p_data, dict):
                p_data = json.loads(p_data)
            p_data['View'] = view
            p_data['CashierInfo'] = {"ClassesID":session.get('ClassesID'),"UserName":current_user.UserName,"CashierName":current_user.CashierName}
            app_logger.debug(f"用户：{current_user.LoginName } 接口：{RouterName}.{view} 数据：{p_data}")
            return PageMessager.post_data_handler(**p_data)
        except Exception as e:
            app_logger.error(f"用户：{current_user.LoginName } 接口：{RouterName}.{view} 错误：{e}")
        return PageMessager.error('處理錯誤，請聯係管理員')
    # GET
    places_snapshot = CarParkService.CarParkPlaces.copy()
    lanes = [CarParkService.EntranceLane, CarParkService.ExitLane]
    lanes_snapshot = [i.snapshot() for i in lanes]
    for i in lanes_snapshot:
        image = i.get("LicensePlateImg")
        if image:
            i['LicensePlateImg'] = url_for('static',filename=image)
    page_data = {"PlacesSnapshot":json.dumps(places_snapshot,ensure_ascii=False),"LanesSnapshot":json.dumps(lanes_snapshot,ensure_ascii=False)}
    return render_template('charge_preview.html', **page_data)


@charge.route('/classes', methods=['POST', 'GET'])
@login_required
def classes():
    """
    更次界面
    """
    view = "classes"
    if request.method == 'POST':
        try:
            # 检查数据类型
            p_data = request.get_json()
            if not isinstance(p_data, dict):
                p_data = json.loads(p_data)
            p_data['View'] = view
            p_data['CashierInfo'] = {"ClassesID":session.get('ClassesID'),"UserName":current_user.UserName,"CashierName":current_user.CashierName}
            app_logger.debug(f"用户：{current_user.LoginName } 接口：{RouterName}.{view} 数据：{p_data}")
            return PageMessager.post_data_handler(**p_data)
        except Exception as e:
            app_logger.error(f"用户：{current_user.LoginName } 接口：{RouterName}.{view} 错误：{e}")
        return PageMessager.error('處理錯誤，請聯係管理員')
    classes_id = session.get('ClassesID')
    if classes_id:
        user_name = current_user.UserName
        cashier_name = current_user.CashierName
        ret = PageMessager.cashier_classes_data(classes_id, cashier_name, user_name)
        return render_template('charge_classes.html', **ret)
    return render_template('charge_classes_guest.html')


@charge.route('/pay', methods=['POST'])
@login_required
def pay():
    """
    缴费
    """
    view = "pay"
    try:
        # 检查数据类型
        p_data = request.get_json()
        if not isinstance(p_data, dict):
            p_data = json.loads(p_data)
        cashier_name = current_user.CashierName
        classes_id = session.get('ClassesID')
        if cashier_name is None:
            return PageMessager.error("用戶沒有綁定收費處！")
        if not classes_id:
            return PageMessager.error("用戶沒有收費更次！")
        p_data['View'] = view
        p_data['CashierInfo'] = {"ClassesID":classes_id,"UserName":current_user.UserName,"CashierName":current_user.CashierName}
        app_logger.debug(f"用户：{current_user.LoginName } 接口：{RouterName}.{view} 数据：{p_data}")
        return PageMessager.post_data_handler(**p_data)
    except Exception as e:
        app_logger.error(f"用户：{current_user.LoginName } 接口：{RouterName}.{view} 错误：{e}")
    return abort(500)
